package generator

import (
	"apidoc2entity/model"
	"fmt"
	"path"
	"strings"
)

type Generator struct {
	Strategy IStrategy
	OutPath  string
}

func (gen *Generator) Generate(ch <-chan *model.BuilderStruct) <-chan *model.Product {
	out := make(chan *model.Product)
	go func() {
		defer close(out)
		for st := range ch {
			//组装数据
			out <- Make(gen, st)
		}
	}()
	return out
}

func Make(gen *Generator, st *model.BuilderStruct) *model.Product {
	res := &model.Product{}
	res.FileDir = path.Join(gen.OutPath, st.PackageCode)
	res.FileName = fmt.Sprintf("%s.%s", TypeFormat(st.StructCode), gen.Strategy.Suffix())
	var buf strings.Builder
	// 头部
	buf.WriteString(gen.Strategy.FormatHead(st))
	// 身体
	buf.WriteString(gen.Strategy.FormatBodyBeg(st))
	// 字段
	for _, field := range st.BFields {
		buf.WriteString(gen.Strategy.FormatField(&field))
	}
	buf.WriteString(gen.Strategy.FormatBodyEnd())
	// 脚部
	foot := gen.Strategy.FormatFoot()
	if len(foot) != 0 {
		buf.WriteString(foot)
	}
	res.Data = buf.String()
	return res
}
